package 算法.链表算法;

/**
 * Created by zzy on 2018/4/25.
 */
public class 合并两个有序链表 {

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }else if(l2==null){
            return l1;
        }
        //创建结果链表,不能两个指针同时移动
        ListNode result=new ListNode(-1);
        ListNode p=result;
        while(l1!=null||l2!=null){
            if(l1==null){
                p.next=new ListNode(l2.val);
                p=p.next;
                l2=l2.next;
                continue;
            }
            if(l2==null){
                p.next=new ListNode(l1.val);
                p=p.next;
                l1=l1.next;
                continue;
            }
            int val1=l1.val;
            int val2=l2.val;

            if(val1<=val2){
                p.next=new ListNode(val1);
                p=p.next;
                l1=l1.next;
            }else{
                p.next=new ListNode(val2);
                p=p.next;
                l2=l2.next;
            }
        }
        //结束后 如果有链表不为空，
        if(l1!=null){
            p.next=l1;
        }else if(l2!=null){
            p.next=l2;
        }
        return result.next;
    }

    public static void main(String[] args) {
        ListNode a=ListNode.createListNode(5);
        ListNode b=ListNode.createListNode(1,2,4);
        ListNode result=mergeTwoLists(a,b);
        System.out.println(123);
    }
}
